 
import { useParams,useNavigate } from "react-router-dom";

import { useSelector ,useDispatch } from "react-redux";
import { deleteStuAsync } from "../redux/slice";
import { useEffect, useState } from "react";
function Detail() {
  const stuList = useSelector((state)=>state.stuList)
  const dispatch = useDispatch()

  const [stu,setStu] = useState(null)
  const params = useParams()
  const navigate = useNavigate()
  const stuId = params.id

  // 查询 id 的学生
  useEffect(()=>{
    for(let i=0;i<stuList.length;i++){
      if(stuList[i].id === stuId){
        setStu(stuList[i])
        break
      }
    }
  },[stuList,stuId])

  const handleDelete = async function(){
    dispatch(deleteStuAsync(stuId))
    navigate('/home')
  }

  const handleEdit = function(){
    navigate(`/add/${stuId}`)
  }

  return ( 
    <div>
      <div>
        <h1>个人名片</h1>
        <button onClick={handleDelete}>删除</button>
        <button onClick={handleEdit}>修改</button>
      </div>
      
      <div>
        <div>姓名：{stu?.name}</div>
        <div>年龄：{stu?.age}</div>
        <div>邮箱：{stu?.email}</div>
        <div>联系方式：{stu?.number}</div>
      </div>
    </div>
   );
}

export default Detail;